package com.wjp.banquet.common.filter;

import com.wjp.banquet.common.enums.ResponseEnum;
import com.wjp.banquet.common.exception.BusinessException;
import com.wjp.banquet.common.util.*;
import com.wjp.banquet.entity.User;
import com.wjp.banquet.service.UserService;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author 王君平
 * @Date 2023/8/30 11:48
 * @Description
 */
@Slf4j
public class LoginCheckFilter implements Filter {

    private UserService userService;

    public LoginCheckFilter(
            UserService userService
    ) {
        this.userService = userService;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        try {
            String url = request.getRequestURI();
            if (this.isNotNeedLogin(url, request.getMethod())) {
                //log.info("==============1进入loginFilter了,url=" + url + ",userId=" + UserUtil.getCurrentUserId());
                filterChain.doFilter(request, response);
                return;
            }

            User user = (User)request.getSession().getAttribute(UserUtil.USER_INFO);
            //这一步代码要放在前面  虽然也免登录，但是可能是用户登录了，访问了免登录接口
            if(user == null){
                ResponseUtil.writeErrorResponse(MessageUtil.fail(ResponseEnum.UNAUTHORIZED.getCode(),"用户未登录",null), response);
                return;
            }
            UserUtil.setUserLoginVO(user);
            filterChain.doFilter(request,response);
        }catch (Exception e){
            e.printStackTrace();
            String errorMsg = null;
            if(e instanceof BusinessException){
                BusinessException businessException = (BusinessException)e;
                errorMsg = businessException.getMsg();
            }
            if(StringUtil.isEmpty(errorMsg)){
                errorMsg = e.getMessage();
            }

            if(StringUtil.isEmpty(errorMsg)){
                errorMsg = ExceptionUtil.getStackTrace(e);
            }
            log.error(errorMsg);
            ResponseUtil.writeErrorResponse(MessageUtil.fail(ResponseEnum.FAIL.getCode(),errorMsg,null), response);
        } finally {
            UserUtil.remove();//防止脏数据
        }
    }

    @Override
    public void destroy() {}


    private boolean isNotNeedLogin(String url,String method){
        return "/sys/user/login" .equals(url) || "/sys/user/logout" .equals(url);
    }

}

